$(function () {
    initSqlStatementApi();

    $(".api-box").on("click",".print",function (){
        var json = {};
        var param = decodeURIComponent(location.search.substring(1));
        param.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
            var k = decodeURIComponent(key);
            var v = decodeURIComponent(value);
            if((/\[\]$/).test(k)){
                k = k.substring(0,k.length-2);
                if(!Array.isArray(json[k])){
                    json[k] = [];
                }
                json[k].push(v);
            }else {
                json[k] = v;
            }
        });
        $.ajax({
            method: 'POST',
            url: '/dms/print',
            contentType: 'application/json',
            data: JSON.stringify(json),
            xhrFields: {
                responseType: "blob"
            },
            success: function (data, status, xhr) {
                var  contentDisposition = xhr.getResponseHeader("Content-Disposition");
                var filename = contentDisposition.replace('attachment;filename=', '');
                var link = document.createElement('a'); // 创建一个a标签
                var url = window.URL.createObjectURL(data); // 将Blob对象转换为可下载的链接
                link.href = url;
                link.download = filename; // 设置下载的文件名
                link.click(); // 模拟点击链接进行下载
                window.URL.revokeObjectURL(url);
           }
        });
    });
});

function initSqlStatementApi() {
    var json = {};
    var param = decodeURIComponent(location.search.substring(1));
    param.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
        var k = decodeURIComponent(key);
        var v = decodeURIComponent(value);
        if((/\[\]$/).test(k)){
            k = k.substring(0,k.length-2);
            if(!Array.isArray(json[k])){
                json[k] = [];
            }
            json[k].push(v);
        }else {
            json[k] = v;
        }
    });
    json.expand = true;
    $.ajax({
        url: "/dms/query",
        method: "post",
        dataType: "json",
        data : JSON.stringify(json),
        contentType: 'application/json',
        success: function (response) {
            for(var i = 0 ; i < response.length ; i++){
                var data = response[i];
                data.id = "/"+data.id.replace(/\./g,"/");
                renderMappedStatementAPI(data,i);
            }
        }
    });
}

function renderMappedStatementAPI(data,index) {
    if(!data.rest){
        return;
    }
    var html = [];
    var bookmarks = [];
    var id = "api-item-"+index;
    bookmarks.push("<bookmark name='"+data.name+"' href='#"+id+"'></bookmark>");
    var formId = 'apiDetail'+index;
    html.push("<div class='api-group' id='"+id+"'>");
    html.push("<form id='"+formId+"' >");


    html.push("<div class=\"form-group row\">");
    html.push("<label  class=\"col-sm-6 col-form-label col-form-label-name\">"+data.name+"</label>");
    html.push("</div>");

    html.push("<div class=\"form-group row\">");
    html.push("<span  class=\"col-sm-2 col-form-label col-form-label-name\">"+data.method+"</span>");
    html.push("<span  class=\"col-sm-8 col-form-label col-form-label-name\">"+data.id+"</span>");
    html.push("</div>");

    html.push("</form>");


    var tables = [
        {
            id : "requestHeaderTable"+index,
            title : "请求头",
            field : "requestHeader",
        },
        {
            id : "inputParameterTable"+index,
            title : "请求参数",
            field : "inputParameter",
        },
        {
            id : "outputParameterTable"+index,
            title : "响应参数",
            field : "outputParameter",
        }
    ];
    //初始化入参、出参
    for(var item in tables){
        var table = tables[item];
        html.push("<div class=\"api-box-table\">");
        html.push("<h5>"+table.title+"</h5>");
        html.push("<table id=\""+table.id+"\" class=\"api-parameter\"></table>");
        html.push("</div>");
    }
    html.push("</div>");

    $("#bookmarks").append(bookmarks.join(""));
    $("#api-container").append(html.join(""));

    //初始化数据
    $("#"+formId).deserializable(data);
    for(var i = 0 ;i < tables.length ; i++){
        initSingleParameterTable($("#"+tables[i].id)[0],data[tables[i].field],i);
    }
}


function initSingleParameterTable(element,data,i) {
    var columns;
    if(i == 0){
        columns = [
            {field : "id",title : "id",visible:false},
            { field: "field", title : "键", align : "center",valign : "middle"},
            { field: "defaultValue", title : "值", align : "center",valign : "middle"},
            { field: "name", title : "名称", align : "center",valign : "middle"},
            { field: "required", title : "必填", align : "center",valign : "middle",formatter : function (value, row, index) {
               return row.validator && row.validator.required && !(row.validator.required === "false") ? "是" : "否";
            }},
            { field: "remarks", title : "备注",align : "left",formatter : function (value, row, index){
                   return value ? value.replace(/[\r\n|\n]+/g,"</br>") : "";
            }},
        ];
    }else {
        columns = [
            { field: "field", title : "参数"},
            { field: "name", title : "名称",align : "center"},
            { field: "mergeType", title : "类型",align : "center" ,formatter: function (value, row, index) {
                    var type = row.type ;
                    if(row.type){
                        type = row.genericType ?  row.type+"("+row.genericType+")" : type;
                    }else {
                        type = "";
                    }
                    return type;
                }},
            { field: "required", title : "必填", align : "center",valign : "middle",formatter : function (value, row, index) {
                    return row.validator && row.validator.required && !(row.validator.required === "false") ? "是" : "否";
                }},
            { field: "remarks", title : "备注",align : "left",formatter : function (value, row, index){
                    return value ? value.replace(/[\r\n|\n]+/g,"</br>") : "";
            }},
        ];
    }
    $(element).bootstrapTreeTable({
        data :data,
        showColumns : false,
        showRefresh : false,
        expandAll:true,
        width: "100%",
        striped: true,
        columns :  columns
    });

}